package biznussoft.metercor.fragments;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.ServiceOrderAdapter;
import biznussoft.metercor.listeners.ActivityDetailListener;
import biznussoft.metercor.listeners.InventoryListener;
import biznussoft.metercor.model.ActivityModel;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.InstalProductModel;
import biznussoft.metercor.model.ItemModel;
import biznussoft.metercor.model.MapModel;
import biznussoft.metercor.model.ServiceOrderModel;
import biznussoft.metercor.model.TechnicianModel;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ServiceOrderFragment  extends BaseFragment implements OnItemClickListener{
	private RestClient client;
	public static ArrayList<Bean_Class> list;
	public static ArrayList<TechnicianModel> technicianList;
	public static ArrayList<InstalProductModel> instalProductList;
	public static ArrayList<ItemModel> manufacturerList;
	public static ArrayList<ItemModel> modelList;
	private ListView lv;
	static ArrayList<ServiceOrderModel> serviceOrderList;
	public static ArrayList<MapModel> mapList;
	static ArrayList<ActivityModel> serviceOrderSubList;
	static HashMap<String, ArrayList<ActivityModel>> activityDetailsList;
	private InventoryListener listener;
	private ActivityDetailListener listener1;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.inventory, null);
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem mytrack = menu.add("MyTrack");
		MenuItemCompat.setShowAsAction(mytrack, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		mytrack.setIcon(R.drawable.track); 
		/*MenuItem addwater = menu.add("Water Meter Data Management");                 
		MenuItemCompat.setShowAsAction(addwater,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addwater.setIcon(R.drawable.add);
		MenuItem addGas = menu.add("Gas Meter Management");                 
		MenuItemCompat.setShowAsAction(addGas,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addGas.setIcon(R.drawable.add);*/
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 



	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		if(item.getTitle().equals("MyTrack")){
			listener1.getCategory("Track", "");
		}
		/*if(item.getTitle().equals("Water Meter Data Management")){
			listener1.getCategory("Water", "");
		}
		if(item.getTitle().equals("Gas Meter Management")){
			listener1.getCategory("Gas", "");
		}*/
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (InventoryListener) getActivity();
		listener1 = (ActivityDetailListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);
		Task task = new Task();
		task.execute();     

		lv.setOnItemClickListener(this);

	}

	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{
			String serviceOrder = " SELECT Name,Id,FConnect__Account_Name__c,FConnect__Bill_To_Address__c,FConnect__Contact_Name__c,FConnect__Priority__c,FConnect__Status__c,FConnect__Start_Date__c,Entitlement_Group__c,Service_Name__c,Technician_Name__c,(SELECT Id,Name,Activity_Name__c,FConnect__Status__c,FConnect__Planned_End_Date_Time__c,FConnect__Planned_Start_DateTime__c,FConnect__Duration__c,FConnect__Billable__c FROM FConnect__Activities__r) FROM FConnect__Service_Order__c where Technician__c="+"'"+Session.sID+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("NCS","Response is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result         
								.toString());

						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");

						serviceOrderList = new ArrayList<ServiceOrderModel>();
						mapList = new ArrayList<MapModel>();
						activityDetailsList = new HashMap<String, ArrayList<ActivityModel>>();

						Gson _gson = new Gson();
						for (int i = 0; i < jsonArray.length(); i++) {


							serviceOrderSubList = new ArrayList<ActivityModel>();

							if (!jsonArray.isNull(i)) {
								/*ServiceOrderModel bean = _gson.fromJson(
										jsonArray.getString(i),
										ServiceOrderModel.class);

								serviceOrderList.add(bean);*/


								ServiceOrderModel bean = _gson.fromJson(jsonArray.getString(i),ServiceOrderModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								String billingAddress = jsonArray.getJSONObject(i).getString("FConnect__Bill_To_Address__c");

								if(billingAddress.length()>10){
									if(billingAddress.contains(" ")){
										String address = billingAddress.replace(" ", "%20");
										new MapTask().execute(address,billingAddress);                

									}
								}

								JSONObject siteObject = jsonArray.getJSONObject(i);
								try{
									if (siteObject.getJSONObject("FConnect__Activities__r") != null) {
										JSONArray siteArray = siteObject.getJSONObject("FConnect__Activities__r").getJSONArray("records");

										for (int j = 0; j < siteArray.length(); j++) {
											if (!siteArray.isNull(j)) {
												ActivityModel bean1 = _gson.fromJson(
														siteArray.getString(j),
														ActivityModel.class);



												serviceOrderSubList.add(bean1);
											}

										}
										activityDetailsList.put(ID,serviceOrderSubList);       
										serviceOrderList.add(bean);
									}
								}catch (Exception e) {                 
								}


							}

						}

						showRecords();




					} catch (Exception e) {

						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}


		try{

			String accounts = "select id,name from Model__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {            
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						modelList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								modelList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}





		try{
			String serviceOrder = "select Id,Name from FConnect__Group_Members__c where Id="+"'"+Session.sID+"'";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);
			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try { 
						Log.i("NCS","FConnect__Group_Members__c is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						technicianList = new ArrayList<TechnicianModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								TechnicianModel bean = _gson.fromJson(jsonArray.getString(i), TechnicianModel.class);
								technicianList.add(bean);
							}
						}                        


					} catch (Exception e) {
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});

		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}


		try{
			String serviceOrder = "Select Id,Name from FConnect__Installed_Products__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);
			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try { 
						Log.i("NCS","FConnect__Installed_Products__c is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						instalProductList = new ArrayList<InstalProductModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								InstalProductModel bean = _gson.fromJson(jsonArray.getString(i), InstalProductModel.class);
								instalProductList.add(bean);
							}
						}                        


					} catch (Exception e) {
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});

		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}





		try{               
			String accounts = "Select Id,Name from Account";


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {           

						Log.i("NCS","accounts :"+result);

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						list = new ArrayList<Bean_Class>();




						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{

							if(!jsonArray.isNull(i)){
								Bean_Class bean = _gson.fromJson(jsonArray.getString(i), Bean_Class.class);
								list.add(bean);            
							}
						}


						showRecords();

					} catch (Exception e) {
						Log.i("NCS","Exception  1 is  :"+e.getMessage());
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}


		try{

			String accounts = "select id,name from Manufacturer__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {    

						Log.i("TPT","RestResponse  2 is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						manufacturerList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								manufacturerList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}


	}


	public void showRecords(){
		ServiceOrderAdapter adapter = new ServiceOrderAdapter(getActivity(),serviceOrderList);
		lv.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		ServiceOrderModel model = serviceOrderList.get(position);
		Session.sServiceOrderId = model.getSiteName();                
		setHasOptionsMenu(false);                
		listener.onWarehouseClicked(position,"ServiceOrder");
	}

	class MapTask extends AsyncTask<String, Void, Void>{

		@Override
		protected Void doInBackground(String... params) {
			getLocationInfo(params[0],params[1]);
			return null;
		}                 



	}

	public  void getLocationInfo(String address,String addess2) {

		try{
			//		http://maps.google.com/maps/api/geocode/json?address=10 Main Rd., New York, NY, USA, 31349&sensor=false
			HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address="+address+"&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response;
			StringBuilder stringBuilder = new StringBuilder();

			try {
				response = client.execute(httpGet);                                                  
				HttpEntity entity = response.getEntity();
				InputStream stream = entity.getContent();
				int b;
				while ((b = stream.read()) != -1) {
					stringBuilder.append((char) b);
				}
			}  catch (Exception e) {

				Log.i("TPT", "Exception 1 is  :  " + e.getMessage());
			}

			JSONObject jsonObject = new JSONObject();
			try {
				jsonObject = new JSONObject(stringBuilder.toString());
				getGeoPoint(jsonObject ,addess2);
			} catch (Exception e) {
				Log.i("TPT", "Exception 2 is  :  " + e.getMessage());
			}
		}catch(Exception ex){
			Log.i("TPT", "Main Exception  is  :  " + ex.getMessage());
		}


	}

	public  void getGeoPoint(JSONObject jsonObject,String address) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			MapModel model = new MapModel();


			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lng");

			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lat");


			model.setLatitude(lat);
			model.setLongitude(lon);
			model.setAddress(address);

			mapList.add(model);



		} catch (Exception e) {
			Log.i("NCS", "Exception  3 is  :  " + e.getMessage());
		}


	}


}
